package cn.caijiapeng.spt.ctrl.admin;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.util.Properties;

import com.jfinal.core.Controller;
import com.jfinal.kit.Kv;

import cn.caijiapeng.spt.bean.Resp;
import cn.caijiapeng.spt.config.WebConst;
import cn.caijiapeng.spt.model.SysAccess;
import cn.caijiapeng.spt.service.SysAccessService;
import cn.caijiapeng.spt.service.SysLoginLogService;
import oshi.SystemInfo;
import oshi.hardware.GlobalMemory;
import oshi.util.FormatUtil;

public class AdminCtrl extends Controller{
	public void index() {
		renderJson(Resp.ok());
	}
	
	public void logout() {
		SysAccess sysAccess = getAttr(WebConst.LOGIN_SYS_ACCESS);
		SysAccessService.srv.logout(sysAccess.getStr("token"));
		renderJson(Resp.ok());
	}
	
	public void loginLog() {
		Integer pageNumber = getParaToInt("pageNumber", 1);
		Integer pageSize = getParaToInt("pageSize", 20);
		renderJson(Resp.ok(SysLoginLogService.srv.getPage(pageNumber, pageSize)));
	}
	
	public void info() {
		Kv jvm = Kv.create();
		Kv os = Kv.create();
		Properties props=System.getProperties(); //系统属性 
		Runtime r = Runtime.getRuntime();
		RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean();
		SystemInfo si = new SystemInfo();
		GlobalMemory memory = si.getHardware().getMemory();
		
		os.set("curtime", System.currentTimeMillis());
		os.set("name", props.getProperty("os.name"));
		os.set("version", props.getProperty("os.version"));
		os.set("arch", props.getProperty("os.arch"));
		os.set("cpu_count", r.availableProcessors());
		os.set("free_memory", FormatUtil.formatBytes(memory.getAvailable()));
		os.set("total_memory", FormatUtil.formatBytes(memory.getTotal()));
		
		jvm.set("jvm_name", props.getProperty("java.vm.name"));
		jvm.set("version", props.getProperty("java.version"));
		jvm.set("total_memory", FormatUtil.formatBytes(r.totalMemory()));
		jvm.set("free_memory", FormatUtil.formatBytes(r.freeMemory()));
		jvm.set("max_memory", FormatUtil.formatBytes(r.maxMemory()));
		long startTime = bean.getStartTime();
		jvm.set("start_time", startTime);
		jvm.set("run_time", System.currentTimeMillis() - startTime);
		renderJson(Resp.ok(Kv.by("jvm", jvm).set("os", os)));
	}
}
